package edu.cs335pl.questionnaire.service.impl;


import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itextpdf.text.*;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.LineSeparator;
import edu.cs335pl.questionnaire.mapper.UserMapper;
import edu.cs335pl.questionnaire.pojo.ServerResponse;
import edu.cs335pl.questionnaire.pojo.entity.*;
import edu.cs335pl.questionnaire.service.UserService;
import edu.cs335pl.questionnaire.util.JWTutils;
import edu.cs335pl.questionnaire.util.ReportDemo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    private static Font titleFont = FontFactory.getFont(FontFactory.HELVETICA, 18f, Font.BOLD, new BaseColor(112, 173, 71));
    private static Font subTitleFont = FontFactory.getFont(FontFactory.TIMES_BOLD, 15f, Font.NORMAL, new BaseColor(134, 195, 65));
    private static Font contentFont = FontFactory.getFont(FontFactory.HELVETICA, 12f, Font.NORMAL, new BaseColor(96, 95, 95));

    @Override
    public ServerResponse login(Login login, HttpServletResponse response) {
        User user1 = common(login.getAccount());
        if (user1 == null) {
            return ServerResponse.ofError("用户不存在");
        }
        //密码匹配
        if (login.getPassword().equals(user1.getPassword())) {
            String token = JWTutils.sign(user1.getId(), user1.getCompany());
            response.addHeader("loginuser", token);
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("user", user1);
            return ServerResponse.ofSuccess("成功！", map);
        } else { //密码不匹配
            return ServerResponse.ofError("用户名或密码错误！");
        }
    }


    @Override
    public File generateFile(User user) throws FileNotFoundException, DocumentException {
        int legal_point = user.getLegal_point();
        int hours_point = user.getHours_point();
        int pp_point = user.getPp_point();
        int er_point = user.getEr_point();
        int pm_point = user.getPm_point();
        int tt_point = user.getTt_point();
        int rr_point = user.getRr_point();
        int cr_point = user.getCr_point();
        int pb_point = user.getPb_point();
        int ece_point = user.getEce_point();
        int hs_point = user.getHs_point();
        int covid_point = user.getCovid_point();
        int erg_point = user.getErg_point();

        int[] scorelist = {legal_point, hours_point, pp_point, er_point, pm_point, tt_point, rr_point, cr_point, pb_point, ece_point, hs_point, covid_point, erg_point};

        String filename = user.getCompany() + "_Analysis.pdf";
        String address = "C:/Users/Administrator/Desktop/xxx/" + filename;

        File file = null;
        try {
            file = makeFile(scorelist, address);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    @Override
    public int submit(Questionnaire questionnaire) {
        User user1 = common(questionnaire.getAccount());
        if (user1 == null) {
            return 0;
        }
        BeanUtils.copyProperties(questionnaire, user1);
        return userMapper.updateById(user1);
    }

    @Override
    public User find(String account) {
        User user1 = common(account);
        if (user1 == null) {
            return null;
        } else {
            return user1;
        }
    }

    @Override
    public int editPassword(Login login) {
        User user1 = common(login.getAccount());
        if (user1 == null) {
            return 0;
        }
        user1.setPassword(login.getPassword());
        return userMapper.updateById(user1);
    }

    @Override
    public int updateInfo(CorporateInformation corporateInformation) {
        User user1 = common(corporateInformation.getAccount());
        if (user1 == null) {
            return 0;
        }
        BeanUtils.copyProperties(corporateInformation, user1);
        return userMapper.updateById(user1);
    }

    @Override
    public int updateInfo2(CorporateInformation2 corporateInformation) {
        User user1 = common(corporateInformation.getAccount());
        if (user1 == null) {
            return 0;
        }
        BeanUtils.copyProperties(corporateInformation, user1);
        return userMapper.updateById(user1);
    }

    @Override
    public int saveUser(Login login) {
        if (common(login.getAccount()) != null) {
            return 0;
        }
        User user = new User();
        BeanUtils.copyProperties(login, user);
        return userMapper.insert(user);
    }

    @Override
    public List<QuestionnaireResults> getReport(String account) {
        User user = common(account);
        if (user == null) {
            return null;
        }
        int legal_point = user.getLegal_point();
        int hours_point = user.getHours_point();
        int pp_point = user.getPp_point();
        int er_point = user.getEr_point();
        int pm_point = user.getPm_point();
        int tt_point = user.getTt_point();
        int rr_point = user.getRr_point();
        int cr_point = user.getCr_point();
        int pb_point = user.getPb_point();
        int ece_point = user.getEce_point();
        int hs_point = user.getHs_point();
        int covid_point = user.getCovid_point();
        int erg_point = user.getErg_point();

        int[] scoreList = {legal_point, hours_point, pp_point, er_point, pm_point, tt_point, rr_point, cr_point, pb_point, ece_point, hs_point, covid_point, erg_point};

        String subTitleList =
                "Legal Compliance" + "\n"
                        + "Hours of Work and Leave" + "\n"
                        + "Policies & Practices" + "\n"
                        + "Employee Relations" + "\n"
                        + "Performance Management" + "\n"
                        + "Training and Development" + "\n"
                        + "Recruitment & Retention" + "\n"
                        + "Change and Reorganisation" + "\n"
                        + "Pay and Benefits" + "\n"
                        + "Employee Communication & Engagement" + "\n"
                        + "Health and Safety" + "\n"
                        + "Covid Related" + "\n"
                        + "Employee Records and GDPR";
        Scanner subTitleSc = new Scanner(subTitleList);

        List<QuestionnaireResults> questionnaireResults = new ArrayList<>();

        for (int i = 0; i < 13; i++) {
            QuestionnaireResults questionnaireResults1 = new QuestionnaireResults();
            questionnaireResults1.setTitle(subTitleSc.nextLine());
            questionnaireResults1.setResults(ReportDemo.analysis(i + 1, scoreList[i]).getContent());
            questionnaireResults.add(questionnaireResults1);
        }
        return questionnaireResults;
    }

    public User common(String account) {
        Map<String, Object> map = new HashMap<>();
        //相当于是select * from user where account = account，第二个account是你传进去的
        map.put("account", account);
        List<User> user = userMapper.selectByMap(map);

        if (user.size() == 0) {
            return null;
        } else {
            return user.get(0);
        }
    }


    //Generate the result file itself
    public static File makeFile(int[] scoreList, String address) throws IOException, DocumentException {

        // 1.新建document对象
        Rectangle pageSize = PageSize.A4;
        Document document = new Document(pageSize, 40, 40, 50, 50);
        // 2.建立一个书写器(Writer)与document对象关联，通过书写器(Writer)可以将文档写入到磁盘中。
        // 创建 PdfWriter 对象 第一个参数是对文档对象的引用，第二个参数是文件的实际名称，在该名称中还会给出其输出路径。
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(address));

        // 3.打开文档
        document.open();

        //设置属性
        //标题
        document.addTitle("this is a title");
        //作者
        document.addAuthor("H__D");
        //主题
        document.addSubject("this is subject");
        //关键字
        document.addKeywords("Keywords");
        //创建时间
        document.addCreationDate();
        //应用程序
        document.addCreator("hd.com");

        //4.添加内容

        //logo
        Image logo = Image.getInstance("https://albatel.ie/wp-content/uploads/2021/03/new-logo.jpg");
        //设置图片的宽度和高度
        logo.scaleAbsolute(385f, 152f);
        logo.scalePercent(30);
        //设置图片位置的x轴和y轴
        logo.setAbsolutePosition(pageSize.getWidth() - (logo.getWidth() * 0.3f) - 30f, pageSize.getHeight() - (logo.getHeight() * 0.3f) - 40f);
        //将图片1添加到pdf文件中
        document.add(logo);

        //标题
        Paragraph title = new Paragraph("Human Resource Health Check Report", titleFont);
        title.setAlignment(Element.ALIGN_LEFT);
        document.add(title);

        //画线
        Paragraph p1 = new Paragraph();
        LineSeparator ls = new LineSeparator(1f, 100, new BaseColor(182, 218, 139), Element.ALIGN_CENTER, 0f);
        p1.add(new Chunk(ls));
        document.add(p1);

        //副标题
        Paragraph[] subTitle = new Paragraph[13];
        String subTitleList =
                "Legal Compliance" + "\n"
                        + "Hours of Work and Leave" + "\n"
                        + "Policies & Practices" + "\n"
                        + "Employee Relations" + "\n"
                        + "Performance Management" + "\n"
                        + "Training and Development" + "\n"
                        + "Recruitment & Retention" + "\n"
                        + "Change and Reorganisation" + "\n"
                        + "Pay and Benefits" + "\n"
                        + "Employee Communication & Engagement" + "\n"
                        + "Health and Safety" + "\n"
                        + "Covid Related" + "\n"
                        + "Employee Records and GDPR";
        Scanner subTitleSc = new Scanner(subTitleList);
        for (int i = 0; i < 13; i++) {
            subTitle[i] = new Paragraph(subTitleSc.nextLine(), subTitleFont);
            subTitle[i].setIndentationLeft(10f);
            subTitle[i].setAlignment(Element.ALIGN_LEFT);
        }

        //生成报告
        for (int i = 0; i < 13; i++) {
            //副标题;
            document.add(subTitle[i]);
            //分类分析结果
            document.add(ReportDemo.analysis(i + 1, scoreList[i]));
        }
        File file = new File(address);
        // 5.关闭文档
        document.close();
        return file;
    }

}
